/*
 recyclemeAppDelegate.m
 Date Created: February 13, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "recyclemeAppDelegate.h"

#import "profilemngt/PMCreateProfileViewController.h"

@implementation recyclemeAppDelegate

@synthesize window,navController,mainMenuViewController;
@synthesize profileList;


#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {
  // Setup navigation controller
	[window addSubview:self.navController.view];
  
  // Initialize Core Data
  NSManagedObjectContext *context=[self managedObjectContext];
  if(!context) {
    //TODO Handle error!
    NSLog(@"Error initializing context!");
  }
  
  // Check if the Official Scores have been created yet, if not (first run), create them. :)
  NSFetchRequest *fetchRequest=[[NSFetchRequest alloc] init];
  NSEntityDescription *officialScoresEntity=[NSEntityDescription entityForName:@"OfficialScore" inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:officialScoresEntity];
  NSError *error;
  NSMutableArray *officialScoresResults=[[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
  
  if( officialScoresResults && [officialScoresResults count]==0) {
    // First time running
    for(int i=0;i<5;i++) {
      [self addOfficialScore:@"KK" withScore:i*100];
    }
  }
  
  
  // Initialize profile list
  profileList=[[PMProfileList alloc] initWithManagedObjectContext:[self managedObjectContext]];
  if( !profileList )
  {
    //TODO Handle error!
    NSLog(@"Error initializing profile list!");
  }
  
  // Initialize the main menu with a valid profile list
  [mainMenuViewController setProfileList:profileList];
  

  // Check if any profiles exist... 
  NSArray *profileListArray=[self.profileList listAllProfiles];
  
  if([profileListArray count]==0)
  {
    NSLog(@"No profiles found. Create new one!");
    PMCreateProfileViewController *createProfileController=
      (PMCreateProfileViewController*)[[PMCreateProfileViewController alloc] initWithProfileList:profileList];
    [[self navController] pushViewController:createProfileController animated:NO];
    [createProfileController release];
  }
  /* THIS IS JUST A TEST - START*/
  // Add a random score to the active profile's score list. This is useful for
  // testing the high scores view. 
  // TODO: Remove this test after scores are entered via sorting game
  //else {
  //  PMProfile *activeProfile=[profileList activeProfile];
  //  NSLog(@"Profile %@",[activeProfile class]);
  //  [activeProfile recordScore:(arc4random()%600) achievedOn:[NSDate date]];
  //}
  /* THIS IS JUST A TEST - END */
  NSLog(@"HERE!!");
  [window makeKeyAndVisible];
}

- (void)addOfficialScore:(NSString *)profileName withScore:(int)score {
  NSManagedObject *scoreObj=[NSEntityDescription insertNewObjectForEntityForName:@"OfficialScore" 
                                                          inManagedObjectContext:[self managedObjectContext]];
  
  [scoreObj setValue:profileName forKey:@"profileName"];
  [scoreObj setValue:[NSNumber numberWithInt:score] forKey:@"score"];
  
  // We do not need to bother saving the object context at this point, because
  // scores are not important. If something fails, we will just recreate them 
  // the next time.
}

/**
 applicationWillTerminate: saves changes in the application's managed object
 context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {	
  NSError *error = nil;
  if (managedObjectContext != nil) {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
      /*
       Replace this implementation with code to handle the error appropriately.
			 
       abort() causes the application to generate a crash log and terminate. You 
       should not use this function in a shipping application, although it may 
       be useful during development. If it is not possible to recover from the
       error, display an alert panel that instructs the user to quit the
       application by pressing the Home button.
       */
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    } 
  }
}


#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent
 store coordinator for the application.
 */
- (NSManagedObjectContext *) managedObjectContext {
  if (managedObjectContext != nil) {
    return managedObjectContext;
  }
	
  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  if (coordinator != nil) {
    managedObjectContext = [[NSManagedObjectContext alloc] init];
    [managedObjectContext setPersistentStoreCoordinator: coordinator];
    
    //Undo Support
    NSUndoManager *anUndoManager = [[NSUndoManager  alloc] init];
    [managedObjectContext setUndoManager:anUndoManager];
    [anUndoManager release];
  }
  return managedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models 
 found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
  if (managedObjectModel != nil) {
    return managedObjectModel;
  }
  managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
  return managedObjectModel;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's
 store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
  }
	
  NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"recycleme.sqlite"]];
	
  NSError *error = nil;
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  
  NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                          [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
  if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                                configuration:nil 
                                                          URL:storeUrl 
                                                      options:options 
                                                        error:&error]) {
  /*
  Replace this implementation with code to handle the error appropriately.
		 
  abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 
  Typical reasons for an error here include:
  * The persistent store is not accessible
  * The schema for the persistent store is incompatible with current managed object model
  Check the error message to determine what the actual problem was.
  */
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  abort();
  }    
	
  return persistentStoreCoordinator;
}


#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
  return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
  [managedObjectContext release];
  [managedObjectModel release];
  [persistentStoreCoordinator release];
    
	[window release];
	[super dealloc];
}


@end

